package com.rjxy.plansystemmanagement.controller.entityController;

import com.rjxy.plansystemmanagement.entity.Result.Result;
import com.rjxy.plansystemmanagement.entity.U_file;
import com.rjxy.plansystemmanagement.service.UFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/UFiles")
@Slf4j
@CrossOrigin(origins = "http://localhost:8080")
public class UFileController {
    @Autowired
    private UFileService uFileService;

    @GetMapping("/{uid}")
    private Result getUFileByUId(@PathVariable Integer uid) {
        log.info("根据id {} 获取用户文件", uid);
        U_file u_file = uFileService.getUFileByUId(uid);
        return Result.success(u_file);
    }

    @PostMapping("/upLodeAvatar")
    public Result upLodeAvatar(@RequestParam("uid") String uid, @RequestParam("file") MultipartFile file) {
        log.info("用户 {} 上传头像", uid);

        // 定义保存路径为 D:/UFile/Avatar
        String basePath = "D:/UFile/Avatar/";
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs(); // 创建目录
        }

        // 生成唯一的文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            return Result.error("文件名不能为空");
        }
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

        // 保存文件到目标路径
        File destFile = new File(basePath + uniqueFileName);
        try {
            file.transferTo(destFile); // 保存文件
        } catch (IOException e) {
            log.error("文件保存失败: {}", e.getMessage());
            return Result.error("文件上传失败");
        }

        // 构造完整的头像URL
        String serverAddress = "http://localhost:8080"; // 替换为后端的实际服务地址
        String avatarUrl = serverAddress + "/avatar/" + uniqueFileName;

        // 更新数据库
        U_file uFile = new U_file(Integer.parseInt(uid), avatarUrl);
        boolean success = uFileService.saveOrUpdateAvatar(uFile);
        if (!success) {
            return Result.error("数据库更新失败");
        }

        log.info("头像上传成功，访问路径: {}", avatarUrl);
        return Result.success(avatarUrl);
    }


}
